<template>
  <div>
    <div class='searchBar'>
      <van-search placeholder="想把车停在哪" show-action v-model="searchPark" @search="SearchNearPark" @cancel="CancelSearch"  style="height: 50px;font-size:15px">
        <div slot="action" @click="CancelSearch"  style='color:#06BF04;margin: 0px 10px;font-size: 16px' >重置</div>
      </van-search>
      <van-cell-group v-if='searchRes'>
        <van-cell v-for='(item,index) in pois' :title="item.name"  :label="item.address" @click='selectMapPoint(index)' />
      </van-cell-group>
    </div>
    <div id='parkMap'>
    </div>
    <!--地点信息弹层-->
    <van-popup v-model="isshowPop" position="bottom" :overlay="false" >
      <div class='dhlogo' style='position: relative;' @click='MapDirect'>
        <div class='tologo' v-if='showLogo'>
          <div style='margin-top: 4px'>
            <img :src=daohangimg />
          </div>
            <div>
              <p>到这去</p>
            </div>
        </div>
      </div>
      <van-panel style="width:100%;height:190px;background: white" >
        <div style="width:100%;height:100%">
          <div class='pitem' style='font-size: 16px'><span>{{parname}}</span></div>
          <div class='pitem' style='font-size: 14px;color:  rgba(0,0,0,0.54)'><span>{{parkAdr}}</span></div>
          <div class='pitem' style='font-size: 14px' v-show='showSYBW'>
            <span style="margin-right:3px;">剩余泊位</span><b style="font-size:16px;color:#5EA3FF">{{hasno}}</b>个
            <!--<span  style="margin-left:20px;">(预计1小时后剩余车位)<b style="font-size:16px;color:#5EA3FF">{{lastnumber}}</b>个</span>-->
          </div>
          <div style='position:fixed;bottom: 0px;width: 100%'>
            <van-button size="large" :style='styleOBJ'  @click='toReservePrk' :disabled='isreserve'>{{reserveTips}}</van-button>
          </div>
        </div>
      </van-panel>
    </van-popup>
    <!--预约选择弹层-->
    <van-popup v-model="chooseMap" style='border-radius: 8px' >
      <van-list style='width: 200px;'>
        <van-cell  style="text-align: center;border-bottom: 1px solid #26C4FE" title="百度地图" @click='chooseMapDirt(1)' />
        <van-cell  style="text-align: center;border-bottom: 1px solid #26C4FE" title="腾讯地图" @click='chooseMapDirt(2)'/>
        <van-cell  style="text-align: center" title="高德地图" @click='chooseMapDirt(3)' />
      </van-list>
    </van-popup>
  </div>
</template>

<script type="text/ecmascript-6">
  import { nearParkInfo, getBaiduCoordinates,saveSearchMap, findWxUserInfo,UserInfoByOpenid,saveGuidancePark } from '../../api/nearPark/nearPark';
  import  geo from '../../utils/geolocation'
  import {baseUrl} from 'config/index'
  let geolocation = new geo("FYXBZ-5YDCW-ILWRQ-OOWLM-AJV7Z-QNFH7", "ZQwechat");
  import { Toast } from 'vant';
  import { Dialog } from 'vant';
  export default {
    name: 'nearPark',
    data() {
      return {
        loadZQOpenid:'', //上级页面传来的的章丘openid
        DHOpenid:'',  //导航用openid
        TcMap: '', // 地图实例对象
        getZQCode:'',
        searchPark: '',
        MapMalerList: [],
        mapmakerGren: '',
        mapmakerRed: '',
        mapmakerOrg: '',
        mapmakerMy:'',
        isshowPop: false,
        daohangimg: '',
        resParkInfo: '', // 传递的预约信息
        startpaoint: '', // 当前点
        startPointBD:'', //  百度系  起点坐标
        startCityBD:'',//  百度系 起点城市
        startPointGD:'', //高德 起点坐标
        endPlacename: '', // 终点名称
        endPoint: '', // 终点坐标
        endPointBD:'', //终点百度坐标
        endPointGD:'',  //终点坐标  高德
        searchService: '',
        pois: '',
        searchRes: false ,// 地图搜索结果
        parname: '',
        parkAdr: '',
        hasno: '',
        BpNowPointLG: '',
        BpNowPointLT: '',
        isreserve: false,
        reserveTips: '停车预约',
        mapmakerGray: '',
        showLogo: true, // 显示logo
        showSYBW: true,  // 剩余泊位数
        lastnumber:'',
        searchPointShow:'', //搜索点的显示
        MarkerSaveArry:[],  // 地图标注数组
        chooseMap:false, // 地图选择
        qqSeacrhService:'',
        styleOBJ:{
          'background-color':'#4997FF',
          color:'white'
        }
      };
    },
    created() {
    },
    mounted() {
      this.getZQCode=this.$route.query.code
      this.loadZQOpenid=this.$route.query.openid
      // 地图初始化
      this.MapInit();
      // ---- 查询用户openid
      findWxUserInfo(this.getZQCode).then((res)=>{
        this.DHOpenid=res.openid
      },(err)=>{
        console.log(err)
      })
      // --引入静态文件
      this.mapmakerGren = require('../nearPark/image/green.png');
      this.mapmakerRed = require('../nearPark/image/red.png');
      this.mapmakerOrg = require('../nearPark/image/orange.png');
      this.daohangimg = require('../nearPark/image/daohang.png');
      this.mapmakerGray = require('../nearPark/image/gray.png');
      this.mapmakerMy=require('../nearPark/image/mypoint.png')
    },
    watch:{
      MapMalerList: {
        handler(newVal, oldVal) {
          this.MapMalerList = newVal;
          this.MapAddMaker();
        },
        deep: true
      },
      reserveTips:{
        handler(newVal,oleVal){
          this.reserveTips=newVal
        },
        deep: true
      }
    },
    methods: {
      // ----地图数据查询
      MapDataSearch(lng,lat,distace) { //配置查询距离
        nearParkInfo(lng,lat,distace).then((res) => {
          if(res.length==0){
            Toast.fail('周边暂无车场');
          }else{
            this.MapMalerList = res;
          }
        }, (err) => {
          Toast.fail('查询失败');
        });
      },
      // ----地图初始化
      MapInit() {
        var that = this;
        //-- 地图对象实例
        this.TcMap = new qq.maps.Map(document.getElementById('parkMap'), {
            // center: new qq.maps.LatLng(36.681780,117.526320),
            zoom: 13,
            mapTypeId:qq.maps.MapTypeId.ROADMAP,
            zoomControl: false,
            draggable: true,
            scrollwheel: true,
            disableDoubleClickZoom: false
          }
        );
        //---服务---
        this.qqSeacrhService = new qq.maps.SearchService({
          // 设置搜索范围
          location: '章丘',
          // 设置动扩大检索区域。默认值true，会自动检索指定城市以外区域。
          autoExtend: false,
          // 检索成功的回调函数
          complete: function(results) {
            that.searchRes = true;
            that.pois = results.detail.pois;
          },
          // 若服务请求失败，则运行以下函数
          error: function(e) {
            Toast.fail('出错了，请重试')
          }
        });
        // 获取定位
        if (this.TcMap !=''|| this.TcMap!=undefined){
          var themap=this.TcMap
          // 定位
          this.MapGetLoation()
          //--- 地图监听事件
          var listener = qq.maps.event.addListener(this.TcMap, 'click', function(e) {
            that.searchRes=false  // 搜索pop
            that.isshowPop = false; // 用于关闭导航pop
            //--地图放大一级
            themap.zoomTo(15)
            //  清除其他标注 只显示点选地点的标注
            that.ClearOverLays()
            // 点击点的标注
            var marker = new qq.maps.Marker({
              position: new qq.maps.LatLng(e.latLng.lat,e.latLng.lng),
              map:themap,
              content: '点选位置'
            });
            //---查询点击地点的周边车场
            that.MapDataSearch(e.latLng.lng,e.latLng.lat,3.00)
            //--将当前点存入数组 便于下次清除
            that.MarkerSaveArry.push(marker)
            }
          );
        }
      },
      // h获取当前定位
      MapGetLoation() {
        geolocation.getLocation(this.getLoationOK, this.getLoationErr)
      },
      // 定位成功回调
      getLoationOK(position) {
        this.startpaoint=position.lat+','+position.lng  //当前点
        this.startPointGD=position.lng+','+position.lat  //高德坐标
        this.TcMap.panTo(new qq.maps.LatLng(position.lat,position.lng));  // 地图中心点
        //--- z坐标点样式
        var Micon = this.mapmakerMy
        var anchor = new qq.maps.Point(15, 25),
          size = new qq.maps.Size(44, 50),
          origin = new qq.maps.Point(0, 0),
          markerIcon = new qq.maps.MarkerImage(Micon,size,origin,anchor);
        // ----当前位置显示
        var marker = new qq.maps.Marker({
          position: new qq.maps.LatLng(position.lat,position.lng),
          map: this.TcMap,
          content: '当前位置'
        });
        // 标注样式
        marker.setIcon(markerIcon);

        this.BpNowPointLG=position.lng  //  传入点精度
        this.BpNowPointLT=position.lat  //  传入点纬度
        // ---根据坐标查询车场
        //查询附近车场
        this.MapDataSearch(position.lng,position.lat,100.00)   //定位后默认查询
        // ---根据坐标显示车场
        this.MapAddMaker()
        //---获取起点坐标  百度系
        getBaiduCoordinates(position.lng,position.lat).then((res)=>{
          this.startPointBD=res.lat+','+res.lng
        },(err)=>{
          // alert('请刷新页面重试')
        })
        //---获取地点所在地区
        this.startCityBD=position.city
      },
      // 定位失败回调
      getLoationErr(){
        Toast.fail('获取定位失败'); //提示
      },
      // ----获取
      // 地图标注
      MapAddMaker(){
        var that=this
        for (var i in this.MapMalerList) {
          if (this.MapMalerList[i].totalBerth < 0) {   // 标识正在建设
            var Micon = this.mapmakerGray
            this.showLogo =false  //隐藏 导航
            this.showSYBW = false   //隐藏泊位数
          } else if(this.MapMalerList[i].totalBerth >0 ) {
            var Micon = this.mapmakerGren
            this.showLogo = true  //显示 导航
            this.showSYBW = true   //显示泊位数
          }
          var _point = new qq.maps.LatLng(this.MapMalerList[i].latitude,this.MapMalerList[i].longitude)  // 坐标点
          var anchor = new qq.maps.Point(15, 25),
              size = new qq.maps.Size(42, 68),
              origin = new qq.maps.Point(0, 0),
            markerIcon = new qq.maps.MarkerImage(Micon,size,origin,anchor);
          var marker = new qq.maps.Marker({
            position: _point,
            map: this.TcMap
          });
          //存储标注
          this.MarkerSaveArry.push(marker)
          // 标注样式
          marker.setIcon(markerIcon);
          // 事件
          qq.maps.event.addListener(marker, 'click', function(e) {
            that.isshowPop  = true
            for (var i in that.MapMalerList) {
              if (e.latLng.lat == that.MapMalerList[i].latitude && e.latLng.lng == that.MapMalerList[i].longitude) {
                that.isshowPop = true;
                that.parname = that.MapMalerList[i].parkName;
                that.parkAdr = that.MapMalerList[i].parkName;
                that.hasno = that.MapMalerList[i].remainderBerth;
                that.lastnumber = parseInt((that.MapMalerList[i].remainderBerth)/3)
                that.endPoint = that.MapMalerList[i].latitude + ',' + that.MapMalerList[i].longitude; // 腾讯系 坐标
                that.endPointBD = that.MapMalerList[i].baiduLatitude + ',' + that.MapMalerList[i].baiduLongitude; // 百度系 坐标
                that.endPointGD = that.MapMalerList[i].longitude + ',' + that.MapMalerList[i].latitude; // 高德度系 坐标
                that.endPlacename = that.MapMalerList[i].parkName;
                if (that.MapMalerList[i].totalBerth < 0) {   // 标识正在建设  停车位为-1
                  that.reserveTips = '正在建设'
                  that.showLogo = false  //隐藏 导航
                  that.showSYBW = false   //隐藏泊位数
                  that.styleOBJ={
                    'color':'#4997FF'
                  }
                  that.isreserve = true
                } else {  //以建设完成
                  that.showLogo = true  //显示 导航
                  that.showSYBW = true   //显示泊位数
                  if (that.MapMalerList[i].canBook==1) {  //不可预状态
                    that.styleOBJ={
                      'color':'#4997FF'
                    }
                    that.isreserve = true
                    that.reserveTips = '暂不支持预约'
                  }else if (that.MapMalerList[i].remainderBerth == 0) {   //可预约但是剩余车位为0
                    that.styleOBJ={
                      'color':'#4997FF'
                    }
                    that.isreserve = true
                    that.reserveTips = '没有车位啦'
                  }else if(that.hasno >= 0){   //可预约 车位还有
                    that.isreserve = false
                    that.styleOBJ={
                      'background-color':'#4997FF',
                      'color':'white'
                    }
                    that.reserveTips = '停车预约'
                  }
                }
                that.resParkInfo = that.MapMalerList[i]
              }
            }
          });
        }
      },
      // ----搜索
      SearchNearPark() {
        //--关闭车场弹窗提示
        this.isshowPop=false
        this.qqSeacrhService.search(this.searchPark);
        this.ClearOverLays() //清除标注
      },
      // ---取消搜索事件
      CancelSearch() {
        var _str=this.startpaoint.split(',')
        var _lat=_str[0]
        var _lng=_str[1]
        this.searchPark=''
        this.TcMap.panTo(new qq.maps.LatLng(_lat,_lng)) // 地图中心点
        //--- 清除标注
        this.ClearOverLays()
        //----查询车场
        this.MapDataSearch(_lng,_lat,100.00)
      },
      // ---清除标注
      ClearOverLays(){
        if (this.MarkerSaveArry.length>0) {
          for (var i in this.MarkerSaveArry) {
            this.MarkerSaveArry[i].setMap(null);
          }
        }
      },
      // ---页面跳转
      toReservePrk() {
        //--- 页面跳转前判断用户信息
        var that=this
        findWxUserInfo(this.getZQCode).then((res)=>{
          debugger
          if(res.phoneNo==null ){  //如果手机号为空
            Dialog.confirm({
              title: '未绑定手机号',
              message: '<p style="text-align:center">当前微信未绑定手机号，是否绑定</p>',
            }).then(() => {
              // on confirm
              that.$router.push({  // 跳转到绑定手机号页面
                path:'/ReserveBindNo',
                query:{
                  code:that.getZQCode,
                  openid:res.openid
                }
              })
            }).catch(() => {
              // on cancel
              return
            });
          }else if(!(res.haveBindCar)){   //如果未绑定车辆
            Dialog.confirm({
              title: '未绑定车辆',
              message: '<p style="text-align:center">当前微信未绑定车辆。是否绑定</p>',
            }).then(() => {
              // on confirm
              that.$router.push({
                path:'/ReserveBindCar',  //跳转绑车页面
                query:{
                  code:that.getZQCode,
                  openid:res.openid
                }
              })
            }).catch(() => {
              // on cancel
              return
            });
          }else{  // 绑定信息  下一步
            // 页面跳转
            var  _codeUrl='http://wx.jinanparking.com/getCode.html?appid=wx7305253d6ea42110&scope=snsapi_base&state=wxPay&redirect_uri='
            var _redirectUrl=baseUrl+'/reservePark'
            var arr={
              parkNO: this.resParkInfo.parkNo,
              parkName:this.resParkInfo.parkName,
              getZQCode:this.getZQCode
            }
            var _params='?parkInfo='+JSON.stringify(arr)
            var _url=_codeUrl+_redirectUrl+_params
            window.location.href=_url
          }
        },(err)=>{  //如果页面么有code 看看页面传参的openid
          if(this.loadZQOpenid!=null){
            var that=this
            //--- 根据openid查询信息
            UserInfoByOpenid(this.loadZQOpenid).then((res)=>{
              if(res.phoneNo==null ){  //如果手机号为空
                Dialog.confirm({
                  title: '未绑定手机号',
                  message: '<p style="text-align:center">当前微信未绑定手机号，是否绑定</p>',
                }).then(() => {
                  // on confirm
                  that.$router.push({  // 跳转到绑定手机号页面
                    path:'/ReserveBindNo',
                    query:{
                      code:that.getZQCode,
                      openid:res.openid
                    }
                  })
                }).catch(() => {
                  // on cancel
                  return
                });
              }else if(!(res.haveBindCar)) {   //如果未绑定车辆
                Dialog.confirm({
                  title: '未绑定车辆',
                  message: '<p style="text-align:center">当前微信未绑定车辆。是否绑定</p>',
                }).then(() => {
                  // on confirm
                  that.$router.push({
                    path: '/ReserveBindCar',  //跳转绑车页面
                    query: {
                      code: that.getZQCode,
                      openid: res.openid
                    }
                  })
                }).catch(() => {
                  // on cancel
                  return
                });
              }else{  //绑定了车 绑定了手机号 去预约
                // 页面跳转
                var  _codeUrl='http://wx.jinanparking.com/getCode.html?appid=wx7305253d6ea42110&scope=snsapi_base&state=wxPay&redirect_uri='
                var _redirectUrl=baseUrl+'/reservePark'
                var arr={
                  parkNO: this.resParkInfo.parkNo,
                  parkName:this.resParkInfo.parkName,
                  getZQCode:this.getZQCode
                }
                var _params='?parkInfo='+JSON.stringify(arr)
                var _url=_codeUrl+_redirectUrl+_params
                window.location.href=_url
              }
            },(err)=>{
                Toast.fail('稍后重试')
              })
          }else{
            Toast.fail('退出重试')
          }
        })
      },
      // 启用地图导航
      MapDirect() {
        this.chooseMap=true
      },
      //  搜索后点击选项
      selectMapPoint(i){
        // ----收起列表
        this.searchRes = false
        this.searchPointShow=''  //提前置空
        this.TcMap.panTo(new qq.maps.LatLng(this.pois[i].latLng.lat,this.pois[i].latLng.lng));  // 地图中心点
        this.TcMap.zoomTo(15)
        this.searchPointShow=new qq.maps.LatLng(this.pois[i].latLng.lat,this.pois[i].latLng.lng)   //搜索点
        // ----当前位置显示
        var marker = new qq.maps.Marker({
          position: this.searchPointShow,
          map: this.TcMap,
          content: '当前位置'
        });
        //---将当前搜索点加入数组,方便清除
        this.MarkerSaveArry.push(marker)
        // ---查询车场
        this.MapDataSearch(this.pois[i].latLng.lng, this.pois[i].latLng.lat,3.00);  //选点后搜索周边3公里的车场
        //--- 上传搜索 存为搜索记录
        var SearchMapRecord={
          latitude:this.pois[i].latLng.lat, //维度
          longitude:this.pois[i].latLng.lng,  //精度
          code:this.ZQCode,
          openid:this.DHOpenid,
          searchPlace:this.pois[i].name
        }
        saveSearchMap(SearchMapRecord).then()
      },
      //---选择地图导航
      chooseMapDirt(key){
        //--- 上传导航记录  /{openId}/{parkNo}
        if(this.DHOpenid==null){  //其他页面跳转回来时 没有code  取不到openid
          saveGuidancePark(this.loadZQOpenid,this.resParkInfo.parkNo,this.resParkInfo.parkName)
        }else{
          saveGuidancePark(this.DHOpenid,this.resParkInfo.parkNo,this.resParkInfo.parkName )
        }

        switch (key){
          case 1:  //百度地图
            window.location.href='http://api.map.baidu.com/direction?origin='+this.startPointBD+'&origin_region='+this.startCityBD
              +'&destination='+this.endPointBD+'&destination_region=济南' +'&mode=driving&output=html&src=th.zq'
            break;
          case 2:
            window.location.href ='https://apis.map.qq.com/uri/v1/routeplan?type=drive&fromcoord=' +
              this.startpaoint + '&to=' + this.endPlacename + '&tocoord=' + this.endPoint + '&referer=ZQwechat'
            break;
          case 3:
            window.location.href='https://uri.amap.com/navigation?from='+this.startPointGD+ '&to='+this.endPointGD+
            '&mode=car&policy=1&src=mypage&coordinate=gaode&callnative=0'
            break;
        }
      }
    },
  };
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
  @import "../../common/stylus/mixin.styl"
  .searchBar{
    display:fixed;
    top:0
    z-index 100
  }
  #parkMap{
    position: relative;
    width: 100%;
    height: 93vh;
  }
.pitem{
  margin-left:10px;
  line-height:40px;
  height:40px;
}
  .tologo{
    position: absolute;
    z-index: 3000;
    top:0px;right:20px;
    width:60px;
    height:60px;
    border:1px solid #508DFF;
    background-image: linear-gradient(-90deg, #508DFF 0%, #26C5FE 100%);
    box-shadow: 0 0 4px 0 rgba(0,0,0,0.20);
    border-radius 50%;
    font-size 12px;
    color :white;
    text-align:center
  }
  .van-field{
    height 40px
  }
</style>
